package com.hls.mvc.core;

import java.io.File;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ConfigReader {
    public static SpringMappings configure(String path)
    {
        SAXBuilder builder = new SAXBuilder();
        SpringMappings springMappings = new SpringMappings();
        Document document;
        try {
            document = builder.build(new File(path));
            Element root = document.getRootElement();
            List<Element> beans =  root.getChildren();
            
            for(Element item : beans)
            {
                if(item.getName().equals("annotation-driven"))
                {
                    springMappings.setAnnotationDriven(true);
                    System.out.println("annotation-driven:"+springMappings.getAnnotationDriven());
                }
                if(item.getName().equals("component-scan"))
                {
                    springMappings.setBasePackage(item.getAttributeValue("base-package"));
                    String strIncludeSub = item.getAttributeValue("include-sub");
                    springMappings.setIncludeSub(strIncludeSub==null?false:strIncludeSub.equals("1")||strIncludeSub.equals("true")?true:false);
                    System.out.println("includeSub:"+springMappings.getIncludeSub());
                }               
                if(item.getName().equals("bean"))
                {
                    if(item.getAttributeValue("class")!=null)
                    {
                        if(item.getAttributeValue("class").contains("InternalResourceViewResolver"))
                        {
                            List<Element> properties = item.getChildren();
                            for(Element property : properties)
                            {
                                if(property.getAttribute("name").getValue().equals("prefix"))
                                {
                                    springMappings.setPrefix(property.getAttribute("value").getValue());
                                }
                                if(property.getAttribute("name").getValue().equals("suffix"))
                                {
                                    springMappings.setSuffix(property.getAttribute("value").getValue());
                                }
                            }
                        }
                    }
                }
            }   
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("error occured when reading the configuration file.");
        }
        return springMappings;
    }
}
